import axios from 'axios';
import {ElLoading, ElMessage, ElMessageBox, ElNotification} from 'element-plus'

export default {
  /**
   * 下载文件
   * @param api
   * 请求地址,必填
   * @param method
   * 请求方式:只支持GET或POST,,可选,默认GET
   * @param params
   * 请求参数:GET请求追加在URL后,POST放在body中,可选
   * @param headers
   * 请求头,可选
   */
  download(api, method, params, headers) {
    let r
    if (method.toLowerCase() === 'post') {
      r = axios.post(api, params, {
        responseType: 'blob',
        headers: {
          'Content-Type': 'application/json; application/octet-stream',
          ...headers
        }
      })
    } else if (!method || method.toLowerCase() === 'get') {
      r = axios.post(api, {
        params: params,
        responseType: 'blob',
        headers: {
          'Content-Type': 'application/json; application/octet-stream',
          ...headers
        }
      })
    } else {
      console.error('只支持以GET或POST请求方式下载')
      return
    }

    r.then((res) => {
      const {data, headers} = res
      if (headers['error-msg']) {
        ElMessage({
          type: 'error',
          message: decodeURIComponent(headers['error-msg']).replace(/[+]/g, ' ')
        })
        return false
      }
      const fileName = headers['content-disposition'].replace(/\w+; filename=(.*)/, '$1')
      const blob = new Blob([data], {type: 'application/vnd.ms-excel'})
      const dom = document.createElement('a')
      const url = window.URL.createObjectURL(blob)
      dom.href = url
      dom.download = decodeURI(fileName)
      dom.style.display = 'none'
      document.body.appendChild(dom)
      dom.click()
      dom.parentNode.removeChild(dom)
      window.URL.revokeObjectURL(url)
    }).catch((err) => {
      ElMessage({
        type: 'error',
        message: err
      })
    })
  }
}